/*
 *    Copyright (c) 2018-2025, proj All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the proj developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: proj
 */

package com.ykht.proj.activity.controller.b;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ykht.proj.activity.Enum.PayStatusEnum;
import com.ykht.proj.activity.dto.CnActivityConsumeRecordDTO;
import com.ykht.proj.activity.entity.CnActivityConsumeRecord;
import com.ykht.proj.activity.entity.CnActivityOrder;
import com.ykht.proj.activity.entity.CnActivityPersonShop;
import com.ykht.proj.activity.service.CnActivityConsumeRecordService;
import com.ykht.proj.activity.service.CnActivityOrderService;
import com.ykht.proj.activity.service.CnActivityPersonShopService;
import com.ykht.proj.common.core.util.R;
import com.ykht.proj.common.log.annotation.SysLog;
import com.ykht.proj.common.security.annotation.Inner;
import com.ykht.proj.common.security.util.SecurityUtils;
import com.ykht.proj.coupon.Enum.UserTypeEnum;
import com.ykht.proj.coupon.api.feign.RemoteShopService;
import com.ykht.proj.coupon.api.feign.RemoteWaiterExtService;
import com.ykht.proj.coupon.entity.CnShop;
import com.ykht.proj.coupon.entity.FxWaiterExt;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;


/**
 * 核销表（消费记录表）
 *
 * @author csg
 * @date 2020-12-23 11:13:32
 */
@RestController
@AllArgsConstructor
@RequestMapping("/b/cnactivityconsumerecord/")
@Api(value = "cnactivityconsumerecord", tags = "核销表（消费记录表）管理")
@Slf4j
public class BnActivityConsumeRecordController {

	private final CnActivityConsumeRecordService cnActivityConsumeRecordService;
	private final CnActivityOrderService cnActivityOrderService;
	private final CnActivityPersonShopService cnActivityPersonShopService;

	private final RemoteShopService remoteShopService;

	private final RemoteWaiterExtService remoteWaiterExtService;


	/**
	 * 修改消费记录列表
	 *
	 * @param req
	 * @return
	 */
	@ApiOperation(value = "修改消费记录列表")
	@SysLog("修改消费记录列表")
	@PostMapping("updateCnActivityConsumeRecord")
	public R updateCnActivityConsumeRecord(@RequestBody CnActivityConsumeRecordDTO req) {
		try {
			log.info("->修改消费记录列表", JSONUtil.toJsonStr(req));
			CnActivityConsumeRecord activityConsumeRecord = BeanUtil.toBean(req, CnActivityConsumeRecord.class);
			activityConsumeRecord.setUpdateUser(SecurityUtils.getUserId());
			activityConsumeRecord.setUpdateTime(LocalDateTime.now());
			boolean updateById = cnActivityConsumeRecordService.updateById(activityConsumeRecord);
			return R.ok("修改成功");
		} catch (Exception e) {
			e.printStackTrace();
			return R.failed();
		}
	}


	/**
	 * 添加消费记录列表
	 *
	 * @param req
	 * @return
	 */
	@ApiOperation(value = "添加消费记录列表")
	@SysLog("添加消费记录列表")
	@PostMapping("addCnActivityConsumeRecord")
	public R addCnActivityConsumeRecord(@RequestBody CnActivityConsumeRecordDTO req) {
		try {
			log.info("->添加消费记录列表", JSONUtil.toJsonStr(req));
			CnActivityConsumeRecord activityConsumeRecord = BeanUtil.toBean(req, CnActivityConsumeRecord.class);
			CnActivityOrder order = cnActivityOrderService.getById(activityConsumeRecord.getOrderId());
			Integer userType = SecurityUtils.getUser().getUserType();
			Long shopId = null;
			activityConsumeRecord.setVerificationType(2);
			if (UserTypeEnum.WAITER.getValue().equals(userType)){
				FxWaiterExt userExt = remoteWaiterExtService.getUserExt();
				activityConsumeRecord.setWaiterId(userExt.getId());
				activityConsumeRecord.setVerificationType(1);
				activityConsumeRecord.setShopId(userExt.getShopId());
			}
			activityConsumeRecord.setCreateUser(SecurityUtils.getUserId());
			activityConsumeRecord.setCreateTime(LocalDateTime.now());
			activityConsumeRecord.setDelFlag(0);
			activityConsumeRecord.setDisplay(0);
			activityConsumeRecord.setActivityId(order.getActivityId());
			activityConsumeRecord.setActivityName(order.getActivityName());
			activityConsumeRecord.setTransactionId(order.getTransactionId());
			activityConsumeRecord.setPayTime(LocalDateTime.now());
			activityConsumeRecord.setPayStatus(PayStatusEnum.PAY.getValue());
			activityConsumeRecord.setPayAmount(req.getConsumptionAmount().multiply(order.getDiscount().multiply(new BigDecimal(0.1))).setScale(2, BigDecimal.ROUND_HALF_UP));
			cnActivityConsumeRecordService.addCnActivityConsumeRecord(activityConsumeRecord);
			return R.ok(true);
		} catch (Exception e) {
			e.printStackTrace();
			return R.failed();
		}
	}

	/**
	 * 消费记录列表（分页，搜索）
	 *
	 * @param page
	 * @param req
	 * @return
	 */
	@ApiOperation(value = "消费记录列表（分页，搜索）")
	@SysLog("消费记录列表（分页，搜索）")
	@GetMapping("getCnActivityConsumeRecordListPage")
	public R getCnActivityConsumeRecordListPage(Page page, CnActivityConsumeRecordDTO req) {
		try {
			log.info("->消费记录列表（分页，搜索）：{}", JSONUtil.toJsonStr(req));
			Integer userType = SecurityUtils.getUser().getUserType();
			if (UserTypeEnum.WAITER.getValue().equals(userType)){
				FxWaiterExt userExt = remoteWaiterExtService.getUserExt();
				req.setWaiterId(userExt.getId());
			} else {
				req.setSjId(SecurityUtils.getSjId());
				req.setLoginRoleType(userType);
			}
			return R.ok(cnActivityConsumeRecordService.getCnActivityConsumeRecordListPage(page, req));
		} catch (Exception e) {
			e.printStackTrace();
			return R.failed();
		}
	}

	/**
	 * 根据ID 获取消费记录详情
	 *
	 * @param id
	 * @return
	 */
	@ApiOperation(value = "根据ID 获取消费记录详情")
	@SysLog("根据ID 获取消费记录详情")
	@GetMapping("getByIdCnActivityConsumeRecord")
	public R getByIdCnActivityConsumeRecord(Long id) {
		try {
			log.info("->根据ID 获取消费记录详情", id);
			return R.ok(cnActivityConsumeRecordService.getByIdCnActivityConsumeRecord(id));
		} catch (Exception e) {
			e.printStackTrace();
			return R.failed();
		}
	}


	/**
	 * 验证 订单是否合格
	 *
	 * @param req
	 * @return
	 */
	@ApiOperation(value = "验证 订单是否合格")
	@SysLog("验证 订单是否合格")
	@PostMapping("verificationOrder")
	public R verificationOrder(@RequestBody CnActivityConsumeRecordDTO req) {
		try {
			log.info("->验证 订单是否合格", JSONUtil.toJsonStr(req));
			// 获取订单
			CnActivityOrder activityOrder = cnActivityOrderService.getOne(new QueryWrapper<CnActivityOrder>()
					.lambda().eq(CnActivityOrder::getVerificationCode, req.getVerificationCode()));
			if (null == activityOrder) {
				return R.failed("重新输入核销码");
			}
			if (activityOrder.getPastStatus().equals(1)) {
				return R.failed("会员卡无效");
			}
			Integer userType = SecurityUtils.getUser().getUserType();
			Long shopId = null;
			if (UserTypeEnum.WAITER.getValue().equals(userType)){
				FxWaiterExt userExt = remoteWaiterExtService.getUserExt();
				if (null == userExt){
					return R.failed("当前账号没有绑定的门店");
				}
				shopId = userExt.getShopId();
			} else {
				CnShop shop = remoteShopService.getByLoginIdShop();
				if (null == shop) {
					return R.failed("当前账号没有绑定的门店");
				}
				shopId = shop.getId();
			}

			CnActivityPersonShop activityPersonShop = cnActivityPersonShopService.getOne(new QueryWrapper<CnActivityPersonShop>().lambda()
					.eq(CnActivityPersonShop::getOrderId, activityOrder.getId())
					.eq(CnActivityPersonShop::getShopId, shopId));
			if (null == activityPersonShop) {
				return R.failed("请输入该品牌下正确的核销码");
			}
			if (activityOrder.getDiscountTimeStatus().equals(0)
					&& (activityOrder.getDiscountEndTime().isBefore(LocalDateTime.now())
					|| activityOrder.getDiscountStaTime().isAfter(LocalDateTime.now()))) {
				return R.failed("请在会员卡有效期内使用");
			}
			if (activityOrder.getUserConsumptionNumber() != 0) {
				CnActivityPersonShop personShop = cnActivityPersonShopService.getOne(new QueryWrapper<CnActivityPersonShop>().lambda()
						.eq(CnActivityPersonShop::getOrderId, activityOrder.getId())
						.eq(CnActivityPersonShop::getPerId, activityOrder.getPersonId())
						.eq(CnActivityPersonShop::getShopId, shopId));
				if (personShop.getUsageTimes().equals(0)) {
					return R.failed("该门店使用次数已用尽");
				}
			}
			if (req.getConsumptionAmount().compareTo(activityOrder.getConsumptionAmount()) == -1) {
				return R.failed("消费金额不足");
			}
			return R.ok(activityOrder.getId());
		} catch (Exception e) {
			e.printStackTrace();
			return R.failed();
		}
	}

	/**
	 * 下载搜索 核销表（消费记录表）数据
	 *
	 * @param req
	 */
	@ApiOperation(value = "下载搜索 核销表（消费记录表）数据")
	@GetMapping("/exportTemp")
	@Inner(false)
	public void exportTemp(CnActivityConsumeRecordDTO req) {
		cnActivityConsumeRecordService.downloadExcel(req);
	}

}
